package com.lan.schedule;

import static com.lan.schedule.MainActivity.getAlplaBitmap;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import androidx.annotation.Nullable;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class WidgetService extends Service {
    public int id1[] = {R.id.a, R.id.b, R.id.c, R.id.d, R.id.e, R.id.f, R.id.g, R.id.h, R.id.i, R.id.j, R.id.k, R.id.l, R.id.m, R.id.n, R.id.o, R.id.p, R.id.q, R.id.r, R.id.s, R.id.t, R.id.u, R.id.v, R.id.w, R.id.x, R.id.y};
    public int id2[] = {R.id.aa, R.id.ab, R.id.ac, R.id.ad, R.id.ae, R.id.af, R.id.ag, R.id.ah, R.id.ai, R.id.aj, R.id.ak, R.id.al, R.id.am, R.id.an, R.id.ao, R.id.ap, R.id.aq, R.id.ar, R.id.as, R.id.at, R.id.au, R.id.av, R.id.aw, R.id.ax, R.id.ay};
    public int id3[] = {R.id.a, R.id.b, R.id.f, R.id.g, R.id.k, R.id.l, R.id.p, R.id.q, R.id.u, R.id.v, R.id.w, R.id.x, R.id.y, R.id.r, R.id.s, R.id.t, R.id.m, R.id.n, R.id.o, R.id.h, R.id.i, R.id.j, R.id.c, R.id.d, R.id.e};
    public int id4[] = {R.id.aa, R.id.ab, R.id.af, R.id.ag, R.id.ak, R.id.al, R.id.ap, R.id.aq, R.id.au, R.id.av, R.id.aw, R.id.ax, R.id.ay, R.id.ar, R.id.as, R.id.at, R.id.am, R.id.an, R.id.ao, R.id.ah, R.id.ai, R.id.aj, R.id.ac, R.id.ad, R.id.ae};
    String str1[] = new String[26];
    String str2[] = new String[26];
    GradientDrawable.Orientation or[] = {GradientDrawable.Orientation.TL_BR, GradientDrawable.Orientation.BR_TL, GradientDrawable.Orientation.BL_TR, GradientDrawable.Orientation.TR_BL, GradientDrawable.Orientation.TOP_BOTTOM, GradientDrawable.Orientation.BOTTOM_TOP, GradientDrawable.Orientation.LEFT_RIGHT, GradientDrawable.Orientation.RIGHT_LEFT};
    int[][] colorcan = new int[6][3];
    int ifcolor[] = new int[6];
    int grcolor[] = new int[6];

    public void fr() {
        colorcan[3][0] = 0xFFFFFFFF;
        colorcan[5][0] = 0x00FFFFFF;
        colorcan[0][1] = 0xFF000000;
        colorcan[0][2] = 0xFFFF0000;
        for (int i = 0; i < 6; i++) {
            ifcolor[i] = 0;
            grcolor[i] = 5;
        }
        colorcan[5][0] = 0x00FFFFFF;
        colorcan[4][0] = 0xFFFFFFFF;
        colorcan[0][0] = 0xFF000000;
        colorcan[1][0] = 0xFF880000;
        colorcan[2][0] = 0x55ffffff;
        colorcan[3][0] = 0xffeeeeee;
    }
    @SuppressLint("WrongConstant")
    private Bitmap getBitmapGradient(int aa) {
        GradientDrawable drawable1 = new GradientDrawable();
        if(aa==1){
            drawable1.setShape(GradientDrawable.RECTANGLE);
            drawable1.setGradientType(GradientDrawable.RECTANGLE);
            drawable1.setCornerRadius(50);
            if (ifcolor[1] == 0)
                drawable1.setColor(colorcan[1][0]);
            else {
                int[] colors = {colorcan[1][1], colorcan[1][2]};
                drawable1.setColors(colors);
                drawable1.setOrientation(or[grcolor[1]]);
            }
        }else{
            if (ifcolor[2] == 0) {
                drawable1.setShape(GradientDrawable.RECTANGLE);
                drawable1.setGradientType(GradientDrawable.RECTANGLE);
                drawable1.setCornerRadius(50);
                drawable1.setStroke(10, colorcan[3][0]);
                drawable1.setColor(colorcan[2][0]);
            } else {
                int[] cs = {colorcan[2][1], colorcan[2][2]};
                drawable1.setShape(GradientDrawable.RECTANGLE);
                drawable1.setGradientType(GradientDrawable.RECTANGLE);
                drawable1.setCornerRadius(50);
                drawable1.setStroke(10, colorcan[3][0]);
                drawable1.setColors(cs);
                drawable1.setOrientation(or[grcolor[2]]);
            }}
        //我这图片宽高是全局变量mWidth，mHeight
        Bitmap bitmap;
        if (aa == 1)
            bitmap = Bitmap.createBitmap(1000, 744, Bitmap.Config.ARGB_8888);
        else
            bitmap = Bitmap.createBitmap(660, 480, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        drawable1.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        drawable1.draw(canvas);
        return bitmap;
    }

    int fla = -9;
    int ba = 0xffff0000;
    int sh = 0x55ffffff;
    int fo = 0xff000000;
    int alp = 100;
    String fff="5";
    String TAG = "WidgetService ";
    private Timer mTimer;
    private SimpleDateFormat mFormat;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind");
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        File fileEx = this.getExternalFilesDir(null);
        String dir = fileEx.getAbsolutePath() + "/test_abc";
        if (!fileEx.exists()) { // 先根据路径创建文件夹
            fileEx.mkdirs();
        }
        mFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.i(TAG, "更新 widget");
                updateWidget(WidgetService.this);  //更新 widget
            }
        }, 0, 1000 * 10);

    }

    int f = 1;

    public void nori() {

        int j = 0;
        String name1[] = new String[50];
        String loc[] = new String[50];
        int week[][] = new int[50][30];
        int we[] = new int[50];
        int day[] = new int[50];
        int jie[] = new int[50];
        try {
            FileInputStream fileInputStream = openFileInput("test.txt");
            FileChannel fi = fileInputStream.getChannel();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
            j = Integer.parseInt(bufferedReader.readLine());
            //System.out.println("66666666667" + j);
            for (int i = 1; i < j; i++) {
                //  System.out.println("5555555555555");
                name1[i] = bufferedReader.readLine();
                loc[i] = bufferedReader.readLine();
                jie[i] = Integer.parseInt(bufferedReader.readLine());
                day[i] = Integer.parseInt(bufferedReader.readLine());
                we[i] = Integer.parseInt(bufferedReader.readLine());
                for (int p = 1; p <= we[i]; p++) {
                    week[i][p] = Integer.parseInt(bufferedReader.readLine());
                }
            }
//                    String str = null;
//                    while((str = bufferedReader.readLine()) != null)
//                    {
//                        Toast.makeText(AlarmService.this,str, Toast.LENGTH_SHORT).show();
//                    }
            fi.close();
            bufferedReader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String date = null;
        try {
            String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file/th";
            File file = new File(strFilePath, "date.txt");//在创建文件
            file.canRead();
            InputStream ff = null;
            ff = new FileInputStream(file);

            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ff));
            date=bufferedReader.readLine();
            ff.close();
            bufferedReader.close();
//            ba = ba1;
//            sh = sh1;
//            fo = fo1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        String eTime = date;
        long nd = 1000 * 24 * 60 * 60 * 7;// 一天的毫秒数
        long diff = 0;
        long wee = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date curDate = new Date(System.currentTimeMillis());
        String nowtime = simpleDateFormat.format(curDate);
        try {
            diff = simpleDateFormat.parse(nowtime).getTime() - simpleDateFormat.parse(eTime).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        wee = diff / nd + 1;// 计算周数
        //wee=2;
        for (int i = 1; i < 26; i++) {
            int fl = 0;
            int ji;
            ji = i / 5 + 1;
            if (i % 5 == 0) ji = ji - 1;
            int da;
            da = i % 5;
            if (da == 0) da = 5;
            outterLoop:
            for (int g = 1; g < j; g++) {

                if (day[g] - 1 == da && jie[g] == ji) {
                    for (int p = 1; p <= we[g]; p++) {
                        if (wee == week[g][p]) {
                            fl = 1;
                            str1[i] = name1[g] + loc[g];
                            break outterLoop;
                        }
                    }
                }
            }
            if (fl == 0) str1[i] = "";
        }
        // System.out.println("222222");
        fr();
        try {
            String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file/th";
            FileInputStream ff = new FileInputStream(strFilePath + "/th1.txt");
            FileChannel channel = ff.getChannel();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ff));

            fla = Integer.parseInt(bufferedReader.readLine());
            alp = Integer.parseInt(bufferedReader.readLine());
            for (int y = 0; y < 6; y++) {
                ifcolor[y] = Integer.parseInt(bufferedReader.readLine());
                grcolor[y] = Integer.parseInt(bufferedReader.readLine());
                for (int x = 0; x < 3; x++) {
                    colorcan[y][x] = Integer.parseInt(bufferedReader.readLine());
                }
            }

            channel.close();
            bufferedReader.close();
            // System.out.println("8888888888");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //通过 RemoteViews 加载布局文件
        //通过 setTextView 等方法实现对控件的控制
        RemoteViews remoteViews = new RemoteViews(this.getPackageName(), R.layout.notification_small);
        Bitmap bitmap1 = Bitmap.createBitmap(1000, 744, Bitmap.Config.ARGB_8888);
        bitmap1.eraseColor(ba);
        Bitmap bitmap = Bitmap.createBitmap(660, 480, Bitmap.Config.ARGB_8888);
        bitmap.eraseColor(sh);
        Bitmap bi = AlarmService.circle(bitmap,0xFFFFFFFF);
        Bitmap bw = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
        bi=getBitmapGradient(0);
        for (int o = 1; o < 26; o++) {
            remoteViews.setTextViewText(id2[o - 1], str1[o]/*str1[o]*/);
            remoteViews.setTextColor(id2[o - 1], colorcan[0][0]);
            if (str1[o].equals("")) {
                remoteViews.setImageViewBitmap(id1[o - 1], bw);
            } else {
                //remoteViews.setImageViewResource(id1[o-1],R.drawable.radius_border);
                remoteViews.setImageViewBitmap(id1[o - 1], bi);

            }
            System.out.println(fla);

        }
        Drawable drawable = getResources().getDrawable(R.drawable.bg1);

        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;

        Bitmap bitmap2 = bitmapDrawable.getBitmap();
        bitmap2 =  Main2Activity.toRoundCorner(bitmap2, 20);
        if (fla == 1) {
            remoteViews.setImageViewBitmap(R.id.im, getBitmapGradient(1));
        } else if (fla == 2) {
            Uri imageUri;
            Bitmap bbit = null;
            String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/files";
            imageUri = Uri.fromFile(new File(strFilePath, "landx.png"));
            try {
                bbit = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                bbit = getAlplaBitmap(bbit, alp);
                bbit = Main2Activity.toRoundCorner(bbit, 100);
//            bbit=bbit.copy(Bitmap.Config.ARGB_8888,true);
//            bbit= Bitmap.createBitmap(bbit);
                // System.out.println("1010101");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            remoteViews.setImageViewBitmap(R.id.im, bbit);
            // System.out.println("1010102");
        } else {
            remoteViews.setImageViewBitmap(R.id.im, bitmap2);
        };
//        for(int o=1;o<26;o++){
//            System.out.println("00000");
//        remoteViews.setTextViewText(id2[o - 1], str1[o]/*str1[o]*/);
        //      remoteViews.setTextColor(id2[o - 1], fo);
//            if(str1[o].equals("")){
//                remoteViews.setImageViewBitmap(id1[o-1],bw);
//            }else{
//                //remoteViews.setImageViewResource(id1[o-1],R.drawable.radius_border);
//
//            }
//        }
//        if(fla==1){
//            remoteViews.setImageViewBitmap(R.id.im,bitmap1);
//        }else if(fla==2){
//            Uri imageUri;
//            Bitmap bbit = null;
//            String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file";
//            imageUri = Uri.fromFile(new File(strFilePath, "lan.png"));
//            try {
//                bbit = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//            remoteViews.setImageViewBitmap(R.id.im,bbit);
//
//        }else ;

        Intent addIntent = new Intent();
        addIntent.setAction("com.example.xujiafeng.notificationrefresh.addwg");
        remoteViews.setOnClickPendingIntent(R.id.btn, PendingIntent.getBroadcast(WidgetService.this, 10, addIntent, PendingIntent.FLAG_IMMUTABLE));
        ComponentName componentName = new ComponentName(this, MyWidget.class);
        AppWidgetManager.getInstance(this).updateAppWidget(componentName, remoteViews);
        System.out.println("nor");

    }

    private void updateWidget(Context context) {
        if (pp == 1) {
            uu();
            pp++;
        }
        if (f == 1) {
            nori();
            System.out.println("up0000");
        } else {
            System.out.println("up222");

            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_small2);
            try {
                String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file/th";
                FileInputStream ff = new FileInputStream(strFilePath + "/th2.txt");
                FileChannel channel = ff.getChannel();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ff));

                fff =bufferedReader.readLine();
                channel.close();
                bufferedReader.close();
                // System.out.println("8888888888");
            } catch (Exception e) {
                e.printStackTrace();
            }
            String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/files";
            File cacheFile = new File(strFilePath);
            // 上级文件不存在，进行文件夹的创建
            if (fff.equals("20")) { // 先根据路径创建文件夹
                Uri imageUri;
                Bitmap bbit = null;
                imageUri = Uri.fromFile(new File(strFilePath, "landx1.png"));
                try {
                    bbit = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                    bbit = Main2Activity.toRoundCorner(bbit, 100);
//            bbit=bbit.copy(Bitmap.Config.ARGB_8888,true);
//            bbit= Bitmap.createBitmap(bbit);
                    // System.out.println("1010101");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                remoteViews.setImageViewBitmap(R.id.img, bbit);                    }else{
                Drawable drawable = getResources().getDrawable(R.drawable.bg2);

                BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;

                Bitmap bitmap2 = bitmapDrawable.getBitmap();
                bitmap2 =  Main2Activity.toRoundCorner(bitmap2, 20);
                remoteViews.setImageViewBitmap(R.id.img, bitmap2);
            }
            Intent addIntent = new Intent();
            addIntent.setAction("com.example.xujiafeng.notificationrefresh.xwg");
            remoteViews.setOnClickPendingIntent(R.id.btn, PendingIntent.getBroadcast(WidgetService.this, 10, addIntent, PendingIntent.FLAG_IMMUTABLE));


            ComponentName componentName = new ComponentName(this, MyWidget.class);
            AppWidgetManager.getInstance(this).updateAppWidget(componentName, remoteViews);
        }
    }

    public class NotificationReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case "com.example.xujiafeng.notificationrefresh.addwg":
                    f = 2;
                    System.out.println("cas000");
                    RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.notification_small2);
                    try {
                        String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/file/th";
                        FileInputStream ff = new FileInputStream(strFilePath + "/th2.txt");
                        FileChannel channel = ff.getChannel();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(ff));

                        fff =bufferedReader.readLine();
                        channel.close();
                        bufferedReader.close();
                        // System.out.println("8888888888");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    String strFilePath = String.valueOf(Environment.getExternalStorageDirectory()) + "/Android/data/com.lan.schedule/files";
                    File cacheFile = new File(strFilePath);
                    // 上级文件不存在，进行文件夹的创建
                    if (fff.equals("20")) { // 先根据路径创建文件夹
                        Uri imageUri;
                        Bitmap bbit = null;
                        imageUri = Uri.fromFile(new File(strFilePath, "landx1.png"));
                        try {
                            bbit = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                            bbit = Main2Activity.toRoundCorner(bbit, 100);
//            bbit=bbit.copy(Bitmap.Config.ARGB_8888,true);
//            bbit= Bitmap.createBitmap(bbit);
                            // System.out.println("1010101");
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        remoteViews.setImageViewBitmap(R.id.img, bbit);                    }else{
                        Drawable drawable = getResources().getDrawable(R.drawable.bg2);

                        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;

                        Bitmap bitmap2 = bitmapDrawable.getBitmap();
                        bitmap2 =  Main2Activity.toRoundCorner(bitmap2, 20);
                        remoteViews.setImageViewBitmap(R.id.img, bitmap2);
                    }
                    Intent addIntent = new Intent();
                    addIntent.setAction("com.example.xujiafeng.notificationrefresh.xwg");
                    remoteViews.setOnClickPendingIntent(R.id.btn1, PendingIntent.getBroadcast(WidgetService.this, 10, addIntent, PendingIntent.FLAG_IMMUTABLE));


                    ComponentName componentName = new ComponentName(WidgetService.this, MyWidget.class);
                    AppWidgetManager.getInstance(WidgetService.this).updateAppWidget(componentName, remoteViews);
                    break;
                case "com.example.xujiafeng.notificationrefresh.xwg":
                    System.out.println("cas222");
                    f = 1;
                    nori();
                    break;
            }
        }
    }

    public void uu() {
        IntentFilter filter = new IntentFilter();
        filter.addAction("com.example.xujiafeng.notificationrefresh.xwg");
        filter.addAction("com.example.xujiafeng.notificationrefresh.addwg");
        NotificationReceiver mReceiver = new NotificationReceiver();
        registerReceiver(mReceiver, filter);
    }

    static int pp = 1;

    @Override
    public void onDestroy() {
        super.onDestroy();

        mTimer.cancel();
        mTimer = null;
        Log.i(TAG, "onDestory");
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

}
